package jwebtester.security;

import jwebtester.business.services.SessionMapService;
import jwebtester.business.utils.SessionMapKeys;
import jwebtester.dal.provider.SecurityDataProvider;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Scope;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.stereotype.Component;

import domain.entities.Authentication;

@Component
@Scope("singleton")
public class LoginEventListener implements ApplicationListener<AuthenticationSuccessEvent> {

	private static final Logger LOG = LoggerFactory.getLogger(LoginEventListener.class);

	@Autowired
	private transient SecurityDataProvider dataProvider;

	@Autowired
	private transient SessionMapService sessionMapService;

	@Override
	public void onApplicationEvent(final AuthenticationSuccessEvent event) {
		final Authentication authentication = (Authentication) sessionMapService
				.get(SessionMapKeys.CURRENT_AUTH);
		try {
			dataProvider.saveAuthenticationHistory(authentication.getId());
		} catch (Exception e) {
			LOG.error("Error saving authentication successful record", e);
		}
	}
}
